export default {
  namespaced:true,//开启命名空间
  state:{
    cart:JSON.parse(uni.getStorageSync('cart') || '[]')
  },
  mutations:{
    addToCart(state,data){
      const findResult = state.cart.find(x => x.goods_id === data.goods_id);
      if(findResult){
        findResult.goods_count++;
      }else{
        state.cart.push(data)
      }
      // console.log(state.cart);
      this.commit('Cart/saveToStorage')
    },
    saveToStorage(state){
      uni.setStorageSync('cart',JSON.stringify(state.cart))
    },
    updateGooodsState(state,data){
      const res = state.cart.find(x => x.goods_id === data.goods_id)
      if(res){
        res.goods_state = data.goods_state;
         this.commit('Cart/saveToStorage');
      }
    },
    updateGooodsCount(state,data){
      const res = state.cart.find(x => x.goods_id === data.goods_id)
      if(res){
        res.goods_count = data.goods_count;
        // res.goods_price += (data.goods_count-1) * res.goods_price
         this.commit('Cart/saveToStorage');
      }
    },
    removeGoods(state,id){
      state.cart = state.cart.filter(x => x.goods_id !== id)
      this.commit('Cart/saveToStorage');
    },
    updataAllGoodsState(state,data){//全选
      state.cart.map(x => x.goods_state = data);
      this.commit('Cart/saveToStorage');
    }
  },
  actions:{
    addToCart(context,data){
      context.commit('addToCart',data)
    }
  },
  getters:{
    total(state){
      /* let count = 0;
      state.cart.map((i)=>{
        count += i.goods_count
      })
      return count; */
      return state.cart.reduce((pre,cur)=>{
        pre += cur.goods_count;
        return pre;
      },0)
    },
    isFullCheck(state){
      if(state.cart.length === 0) return false;
      return state.cart.every(x => x.goods_state === true)
    },
    checkCount(state){
      return state.cart.filter(x => x.goods_state).reduce((pre,cur)=>{
        pre+=cur.goods_count
        return pre
      },0)
    },
    checkedGoodsAmout(state){
      return state.cart.filter(x => x.goods_state).reduce((pre,cur)=>{
        pre += cur.goods_count * cur.goods_price
        return pre;
      },0).toFixed(2)
    }
  }
}
// state:()=>({})